<template>
  <el-dialog
    title="批量导入学员"
    v-model="visible"
    width="50%"
    @closed="handleClosed"
  >
    <div class="import-dialog-content">
      <div class="upload-area">
        <el-upload
          class="upload-container"
          action="#"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">请选择Excel文件（.xlsx或.xls）</div>
          </template>
        </el-upload>
      </div>
      
      <div class="template-download">
        <h4>导入模板说明</h4>
        <p>1. 请下载导入模板并按照模板格式填写数据</p>
        <p>2. 表格中标记为必填的字段不能为空</p>
        <p>3. 学号为必填且不可重复</p>
        <el-button link @click="handleDownloadTemplate">下载导入模板</el-button>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="importing">开始导入</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  name: 'StudentImportDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    importing: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'submit', 'download-template', 'cancel'],
  setup(props, { emit }) {
    const visible = ref(false)
    const fileList = ref([])

    // 监听visible变化
    watch(() => props.modelValue, (newValue) => {
      visible.value = newValue
    })

    watch(visible, (newValue) => {
      emit('update:modelValue', newValue)
    })

    // 处理文件变化
    const handleFileChange = (file) => {
      fileList.value = [file.raw]
    }

    // 处理文件移除
    const handleFileRemove = () => {
      fileList.value = []
    }

    // 下载导入模板
    const handleDownloadTemplate = () => {
      emit('download-template')
    }

    // 提交导入
    const handleSubmit = () => {
      if (fileList.value.length === 0) {
        return
      }
      
      const formData = new FormData()
      formData.append('file', fileList.value[0])
      
      emit('submit', formData)
    }

    const handleCancel = () => {
      visible.value = false
    }

    const handleClosed = () => {
      // 重置文件列表
      fileList.value = []
    }

    return {
      visible,
      fileList,
      handleFileChange,
      handleFileRemove,
      handleDownloadTemplate,
      handleSubmit,
      handleCancel,
      handleClosed
    }
  }
}
</script>

<style scoped>
.import-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.template-download {
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
  margin-top: 10px;
}

.template-download h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.template-download p {
  margin: 5px 0;
  color: #606266;
}
</style>